import { routerRedux } from 'dva/router';
import { fakeAccountLogin, fakeAccountLogout } from '../services/api';
import { setAuthority } from '../utils/authority';

export default {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(fakeAccountLogin, payload);
      localStorage.setItem("menu",JSON.stringify(response.permissions.menu));
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: true,
          currentAuthority: response.permissions.role,
        },
      });
      // Login successfully
      if (response.message === 'ok') {
        yield put(routerRedux.push('/'));
      }
    },
    *logout(_, { put, select, call }) {
      try {
        // get location pathname
        const urlParams = new URL(window.location.href);
        const pathname = yield select(state => state.routing.location.pathname);
        // add the parameters in the url
        urlParams.searchParams.set('redirect', pathname);
        window.history.replaceState(null, 'login', urlParams.href);
      } finally {
        const response = yield call(fakeAccountLogout);
        localStorage.clear();
        yield put({
          type: 'changeLoginStatus',
          payload: {
            status: false,
            currentAuthority: response.permissions.role,
          },
        });
        yield put(routerRedux.push('/user/login'));
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      if (payload.status){
        setAuthority(payload.currentAuthority);
      }
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};
